//
//  CryptTools.swift
//  Library_y
//
//  Created by JC on 2023/6/6.
//

import UIKit
import CryptoSwift

public class CryptTools: NSObject {
    
    // 文件加密
    static public func file_Encrypt_AES(by pathUrl: URL, _ aesKey: String, complete: BlockSingleBool? = nil) {
        guard let data = try? Data(contentsOf: pathUrl), let str = String(data: data, encoding: String.Encoding.utf8) else { complete?(false); return }
        DispatchQueue.main.async {
            do {
                let s = CryptTools.str_encrypt_AES(str, aesKey)
                let d = s.data(using: String.Encoding.utf8)
                try d?.write(to: pathUrl)
                complete?(true)
            } catch {
                complete?(false)
                Log_y.print_("file_Encrypt_AES = \(error.localizedDescription)")
            }
        }
    }
    
    // 文件解密
    static func file_decrypt_AES(by pathUrl: URL, _ aesKey: String, complete: BlockSingleBool? = nil) {
        guard let data = try? Data(contentsOf: pathUrl), let str = String(data: data, encoding: String.Encoding.utf8) else { complete?(false);  return }
        DispatchQueue.main.async {
            do {
                let s = CryptTools.str_decrypt_AES(str, aesKey)
                let d = s.data(using: String.Encoding.utf8)
                try d?.write(to: pathUrl)
                complete?(true)
            } catch {
                complete?(false)
                Log_y.print_("file_decrypt_AES = \(error.localizedDescription)")
            }
        }
    }
    
    // 字符串加密
    static func str_encrypt_AES(_ str: String, _ aesKey: String) -> String {
        var encodeString = ""
        do{
            let aes = try AES(key: aesKey.bytes, blockMode: ECB(), padding: .pkcs7)
            let encoded = try aes.encrypt(str.bytes)
            encodeString = encoded.toBase64()
        } catch {
            Log_y.print_("str_encrypt_AES = \(error.localizedDescription)")
        }
        return encodeString
    }
    
    // 字符串解密
    static func str_decrypt_AES(_ str: String, _ aesKey: String) -> String {
        var decodeStr = ""
        let data = NSData(base64Encoded: str, options: .ignoreUnknownCharacters)
        var encrypted: [UInt8] = []
        let count = data?.count ?? 0
        for i in 0..<count {
            var temp:UInt8 = 0
            data?.getBytes(&temp, range: NSRange(location: i,length:1 ))
            encrypted.append(temp)
        }
        do {
            let aes = try AES(key: aesKey.bytes, blockMode: ECB(), padding: .pkcs7)
            let decode = try aes.decrypt(encrypted)
            let encoded = Data(decode)
            decodeStr = String(bytes: encoded.bytes, encoding: .utf8) ?? ""
        } catch {
            Log_y.print_("str_decrypt_AES = \(error.localizedDescription)")
        }
        return decodeStr
    }
}
